<?php
// $Id: admin.inc,v 1.133 2008/09/10 21:29:15 merlinofchaos Exp $
/**
 * @file admin.inc
 * Provides the MewDKP UI Interface
 */

/**
 * Submit handler to break_lock a raid.
 */
function mewdkp_ui_break_lock_confirm_submit(&$form, &$form_state) {
  db_query("DELETE FROM {mewdkp_object_cache} WHERE nid = %d", $form_state['raid']->nid);
  $form_state['redirect'] = 'node/' . $form_state['raid']->nid . '/editraid';
  drupal_set_message('The lock has been broken and you may now edit this raid.');
}

/**
 * The main raid edit page
 */
function mewdkp_ui_edit_page($raid) {
	_mewdkp_add_js('base');
  drupal_set_title(t('Edit raid "%raid"', array('%raid' => $raid->title)));
  $output = theme('mewdkp_ui_edit_raid', $raid);
  //mewdkp_ui_check_advanced_help();
  return $output;
}

/**
 * The main edit raid form, which is really just a save/cancel/delete button.
 */
function mewdkp_ui_edit_raid_form(&$form_state, $raid) {
  $form['buttons']['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#validate' => array('mewdkp_ui_edit_raid_form_validate'),
    '#submit' => array('mewdkp_ui_edit_raid_form_submit'),
  );

  $form['buttons']['cancel'] = array(
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#submit' => array('mewdkp_ui_edit_raid_form_cancel'),
  );

  if (is_numeric($raid->vid)) {
    $form['buttons']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#submit' => array('mewdkp_ui_edit_raid_form_delete'),
    );
  }

  $form_state['raid'] = &$raid;
  return $form;
}

/**
 * Validate that a raid is complete and whole.
 */
function mewdkp_ui_edit_raid_form_validate($form, $form_state) {
  // Do not validate cancel or delete.
  if (empty($form_state['clicked_button']['#value']) || $form_state['clicked_button']['#value'] != t('Save')) {
    return;
  }
	
	//TO DO: Proper validation
}

/**
 * Submit handler for the edit raid form.
 */
function mewdkp_ui_edit_raid_form_submit($form, &$form_state) {
  _mewdkp_include('cache');
	node_save($form_state['raid']);
  drupal_set_message(t('The raid has been saved.'));

  // Clear the page cache.
  cache_clear_all();

  // Remove this raid from cache so we can edit it properly.
  mewdkp_cache_clear($form_state['raid']->nid);
}

/**
 * Submit handler for the edit raid form.
 */
function mewdkp_ui_edit_raid_form_cancel($form, &$form_state) {
  // Remove this raid from cache so edits will be lost.
  mewdkp_cache_clear($form_state['raid']->nid);
  if (empty($form['raid']->vid)) {
    // I seem to have to drupal_goto here because I can't get fapi to
    // honor the redirect target. Not sure what I screwed up here.
    drupal_goto('node/' . $form['raid']->nid);
  }
}

function mewdkp_ui_edit_raid_form_delete($form, &$form_state) {
  unset($_REQUEST['destination']);
  // Redirect to the delete confirm page
  $form_state['redirect'] = array('node/' . $form_state['raid']->nid . '/delete', 'cancel=node/' . $form_state['raid']->nid . '/editraid');
}

/**
 * Preprocess the raid edit page.
 */
function template_preprocess_mewdkp_ui_edit_raid(&$vars) {
  $raid = &$vars['raid'];
	$vars['admin'] = user_access('administer mewdkp');

  if (user_access('administer mewdkp')){
		$vars['save_button'] = drupal_get_form('mewdkp_ui_edit_raid_form', $raid);
	};

  //Our tabs is a copy of views ui tabs
	_mewdkp_include('tabs');
	
  $tabs = new mewdkp_tabset;

  $vars['message'] = '<div class="message">' . t("Click on an item to edit that item's details.") . '</div>';

  foreach ($raid->kills as $id => $kill) {
    list($title, $body) = mewdkp_ui_display_tab($raid, $kill);
    $tabs->set($id, $title, $body);
  }

  // This is the area that will render beneath the links
  $form_state = array(
    'raid' => &$raid,
    'ajax' => FALSE,
  );
	
  if (user_access('administer mewdkp')){
		$kill_button = drupal_build_form('mewdkp_ui_add_kill_form', $form_state);
		$tabs->add_extra($kill_button);
	}

  $vars['tabs'] = $tabs->render();

  $form_state = array(
    'nid' => $raid->nid,
    'raid_args' => '',
    'rerender' => FALSE,
    'no_redirect' => TRUE,
    'raid' => &$raid,
    'input' => array(),
  );

  $vars['locked'] = NULL;
  if (isset($raid->locked) && is_object($raid->locked)) {
    $account = user_load($raid->locked->uid);
    $vars['locked'] = theme('username', $account);
    $vars['lock_age'] = format_interval(time() - $vraid->locked->updated);
    $vars['break'] = l(t('break this lock'), 'mewdkp/editor/break-lock/' . $raid->nid);
  }

  $vars['quick_links'] = theme('links', $vars['quick_links_raw']);
  _mewdkp_add_css('mewdkp-ui');
  _mewdkp_add_js('ajax');
  drupal_add_js('misc/jquery.form.js');

  $settings = array('mewdkp' => array('ajax' => array(
    'id' => '#mewdkp-ajax-pad',
    'title' => '#mewdkp-ajax-title',
    'defaultForm' => $vars['message'],
  )));

  drupal_add_js($settings, 'setting');
}

function template_preprocess_mewdkp_ui_edit_tab(&$vars) {
  $raid = $vars['raid'];
  $kill = $vars['kill'];

  $top = $left = $middle = $right = '';

  // If this form was submitted it was already handled, so force it not to
  // submit again.

  $vars['remove'] = '';
  if (empty($plugin['no remove']) && user_access('administer mewdkp')) {
    if (!empty($_POST['form_id']) && $_POST['form_id'] == 'mewdkp_ui_remove_kill_form') {
      unset($_POST['form_id']);
    }
    $form_state = array('raid' => &$raid, 'kill_id' => array_search($kill, $raid->kills), 'ajax' => FALSE);
    $vars['remove'] = drupal_build_form('mewdkp_ui_remove_kill_form', $form_state);
  }

  // basic fields
  $vars['title'] = check_plain($kill['name']);

  // Add a help icon
  //$vars['display_help_icon'] = theme('advanced_help_topic', $plugin['module'], $plugin['help topic']);

  $vars['drops'] = theme('mewdkp_ui_edit_drops', $raid, $kill);
  $vars['attendance'] = theme('mewdkp_ui_edit_attendance', $raid, $kill);
}

/**
 * Generate the summary output for a single kill to render in a tab.
 */
function mewdkp_ui_display_tab($raid, $kill) {
  $body = theme('mewdkp_ui_edit_tab', $raid, $kill);
  return array($kill['name'], $body);
}

/**
 * Add information about drops to a kill
 */
function template_preprocess_mewdkp_ui_edit_drops(&$vars) {
  $raid = $vars['raid'];
  $kill = $vars['kill'];
	$kill_id = array_search($kill, $raid->kills);

  if (user_access('administer mewdkp')){
		$vars['add'] = l('<span>' . t('Add') . '</span>', "mewdkp/editor/nojs/add-drop/$raid->nid/$kill_id", array('attributes' => array('class' => 'mewdkp-button-add mewdkp-ajax-link', 'title' => t('Add')), 'html' => true));
	}
	
  $vars['title'] = t('Drops');
	
  $drops = array();
	//Used for class icons
	static $class = array();
	if (empty($class)) {
		$class = variable_get('mewdkp_lookup_class', array());
	}
	//Process drop output
  foreach ($kill['drops'] as $drop_id => $drop) {
    $drops[$drop_id] = array();
		/* Drops should contain all information needed per row to display the drop.
			 This include the drop wowhead link, the edit icon link, and the displayed winner info, count, and disenchanted flag. */
		$winner = node_load($drop['winner']);
		$item = node_load($drop['nid']);
		if (user_access('administer mewdkp')){
			if ($drop['note'] != '' && is_numeric($drop['note'])){
				$drops[$drop_id]['price'] = $drop['note'];
			} else {
				$drops[$drop_id]['price'] = $item->field_mewdkp_price[0]['value'];
			}
		} else {
			$drops[$drop_id]['price'] = 'Hidden';
		}
		$drops[$drop_id]['name'] = $drop['name'];
		$drops[$drop_id]['link'] = l($item->title,'node/'. $item->nid,array('attributes' => array('class' => 'q'. $item->field_mewdkp_quality[0]['value'])));
		$drops[$drop_id]['wowhead_icon'] = '<div class="wowhead-icon-small" style="background-image: url(http://static.wowhead.com/images/icons/small/'. strtolower($item->field_mewdkp_icon[0]['value']) .'.jpg);"><div class="border"><a href="http://www.wowhead.com/?item=' . $item->field_mewdkp_wowid[0]['value'] . '" target="_blank"></a></div></div>';
		
		if (user_access('administer mewdkp')){
			$drops[$drop_id]['edit'] = l(t("Edit"), "mewdkp/editor/nojs/edit-drop/$raid->nid/$kill_id/$drop_id", array('attributes' => array('class' => 'mewdkp-ajax-link')));
		}
		
		$drops[$drop_id]['disenchanted'] = ($drop['note'] == 'DE');
		$classname = $class[$winner->field_mewdkp_class[0]['value']];
		$link = l($winner->field_mewdkp_player_name[0]['value'], 'node/' . $winner->nid);
		if (variable_get('mewdkp_use_class_colors', FALSE)){
			$link = '<span class="'. strtolower( str_replace(' ', '', $class[$winner->field_mewdkp_class[0]['value']])) .'">' . $link . '</span>'; 
		}
		$drops[$drop_id]['winner'] = array(
			'nid' => $drop['winner'],
			'name' => $winner->field_mewdkp_player_name[0]['value'],
			'class' => $winner->field_mewdkp_class[0]['value'],
			'icon' => '<img src="http://' . $_SERVER['HTTP_HOST'] . '/' . drupal_get_path('module', 'mewdkp') . '/images/icons/c' . $winner->field_mewdkp_class[0]['value'] . '.png" style="vertical-align: middle" title="'. $classname .'" />',
			'link' => $link
		);
		$drops[$drop_id]['changed'] = $raid->changed_sections[$kill_id . '-drop-' . $drop_id];
  }

  $vars['drops'] = $drops;
  $vars['item_help_icon'] = theme('advanced_help_topic', 'mewdkp', 'drop');
}

/**
 * Add information about attendance to a kill
 */
function template_preprocess_mewdkp_ui_edit_attendance(&$vars) {
  $raid = $vars['raid'];
  $kill = $vars['kill'];

	if (user_access('administer mewdkp')){
		$vars['edit'] = l('<span>' . t('Edit') . '</span>', "mewdkp/editor/nojs/edit-attendance/$raid->nid/" . array_search($kill, $raid->kills), array('attributes' => array('class' => 'mewdkp-button-configure mewdkp-ajax-link', 'title' => t('Edit')), 'html' => true));
	}

  $vars['title'] = t('Attendance');
	
	//We cache our player info statically to lessen the use of user_load in large raids.
	static $player_cache = array(); 
	
	//Used for class icons
	static $class = array();
	if (empty($class)) {
		$class = variable_get('mewdkp_lookup_class', array());
	}
		
	//Process attendance output
  $attendance = array();
  if(is_array($kill['attendance'])){
    foreach ($kill['attendance'] as $id => $nid) {
  		if (!empty($player_cache[$nid])) {
  			$player = $player_cache[$nid];
  		}
  		else {
  			$player = node_load($nid);
  			$player_cache[$nid] = $player;
  		}
  		
      $attendance[$id] = array();
  		$attendance[$id]['nid'] = $nid;
  		$attendance[$id]['name'] = $player->field_mewdkp_player_name[0]['value'];
  		$attendance[$id]['class'] = $player->field_mewdkp_class[0]['value'];
  		$attendance[$id]['icon'] = '<img src="http://' . $_SERVER['HTTP_HOST'] . '/' . drupal_get_path('module', 'mewdkp') . '/images/icons/c' . $player->field_mewdkp_class[0]['value'] . '.png" style="vertical-align: middle" title="'. $class[$player->field_mewdkp_class[0]['value']] .'" />';
      if (variable_get('mewdkp_use_class_colors', FALSE)){
  			$attendance[$id]['link'] = '<span class="'. strtolower(str_replace(' ', '', $class[$player->field_mewdkp_class[0]['value']])) .'">'. l($player->field_mewdkp_player_name[0]['value'], 'node/' . $player->nid). '</span>';
  		} else {
  			$attendance[$id]['link'] = l($player->field_mewdkp_player_name[0]['value'], 'node/' . $player->nid);
  		}
    }
  }

  $vars['attendance'] = $attendance;
  $vars['item_help_icon'] = theme('advanced_help_topic', 'mewdkp', 'attendance');
}

/**
 * Regenerate the tabs for AJAX updates.
 */
function mewdkp_ui_regenerate_tabs(&$raid, $kill_id = NULL, $object = NULL) {
  if (!is_object($object)) {
    $object = new stdClass();
  }

  $object->replace = array();
  foreach ($raid->kills as $id => $kill) {
    list($title, $body) = mewdkp_ui_display_tab($raid, $kill);
    $object->replace['#mewdkp-tab-' . $id] = $body;
    $object->replace['#mewdkp-tab-title-' . $id] = $title;
  }
	
	if ($kill_id != NULL){
		$object->remove = $kill_id;
	}

  if ($raid->edited) {
    $object->edited = TRUE;
  }

  mewdkp_ajax_render($object);
}

/**
 * Provide standard buttons for the forms to make it easy. Also provide
 * a hidden op operator because the forms plugin doesn't seem to properly
 * provide which button was clicked.
 */
function mewdkp_ui_standard_form_buttons(&$form, &$form_state, $form_id, $name = NULL, $third = NULL, $submit = NULL) {
  $form['buttons'] = array(
    '#prefix' => '<div class="clear-block"><div class="form-buttons">',
    '#suffix' => '</div></div>',
  );

  if (empty($name)) {
    $name = t('Update');
  }
  // remove default validate handler
  $form['#validate'] = array();

  if (empty($form_state['ok_button'])) {
    // but be sure submit button validates!
    $form['buttons']['submit'] = array(
      '#type' => 'submit',
      '#value' => $name,
      '#submit' => array($form_id . '_submit'),
      '#validate' => array('mewdkp_ui_standard_submit', $form_id . '_validate'),
    );
  }

  $cancel_submit = function_exists($form_id . '_cancel') ? $form_id . '_cancel' : 'mewdkp_ui_standard_cancel';
  $form['buttons']['cancel'] = array(
    '#type' => 'submit',
    '#value' => empty($form_state['ok_button']) ? t('Cancel') : t('Ok'),
    '#submit' => array($cancel_submit),
    '#validate' => array(),
  );

  if ($third) {
    if (empty($submit)) {
      $submit = 'third';
    }
    $third_submit = function_exists($form_id . '_' . $submit) ? $form_id . '_' . $submit : 'mewdkp_ui_standard_cancel';

    $form['buttons'][$submit] = array(
      '#type' => 'submit',
      '#value' => $third,
      '#validate' => array(),
      '#submit' => array($third_submit),
    );
  }

  // Compatibility, to be removed later:
  // We used to set these items on the form, but now we want them on the $form_state:
  if (isset($form['#title'])) {
    $form_state['title'] = $form['#title'];
  }
  if (isset($form['#help_topic'])) {
    $form_state['help_topic'] = $form['#help_topic'];
  }
  if (isset($form['#help_module'])) {
    $form_state['help_module'] = $form['#help_module'];
  }
  if (isset($form['#url'])) {
    $form_state['url'] = $form['#url'];
  }
  if (isset($form['#js'])) {
    if (!empty($form_state['js settings']) && is_array($form_state['js settings'])) {
      $form_state['js settings'] = array_merge($form_state['js settings'], $form['#js']);
    }
    else {
      $form_state['js settings'] = $form['#js'];
    }
  }
  if (isset($form['#section'])) {
    $form_state['#section'] = $form['#section'];
  }
  // Finally, we never want these cached -- our object cache does that for us.
  $form['#no_cache'] = TRUE;

  // If this isn't an ajaxy form, then we want to set the title.
  drupal_set_title($form['#title']);
  _mewdkp_add_css('mewdkp-ui');
}

/**
 * Basic submit handler applicable to all 'standard' forms
 */
function mewdkp_ui_standard_submit($form, &$form_state) {
  if (!empty($form['#section'])) {
    $form_state['raid']->changed_sections[$form['#section']] = TRUE;
  }
}

/**
 * Submit handler for cancel button
 */
function mewdkp_ui_standard_cancel($form, &$form_state) {
  $form_state['redirect'] = 'node/' . $form_state['raid']->nid;
}

// --------------------------------------------------------------------------
// Various subforms for editing the pieces of a raid.

function mewdkp_ui_ajax_forms($key = NULL) {
  $forms = array(
    'add-kill' => array(
      'form_id' => 'mewdkp_ui_add_kill_form',
      'args' => array(),
    ),
    'remove-kill' => array(
      'form_id' => 'mewdkp_ui_remove_kill_form',
      'args' => array(),
    ),
    'add-drop' => array(
      'form_id' => 'mewdkp_ui_add_drop_form',
      'args' => array(),
    ),
    'edit-attendance' => array(
      'form_id' => 'mewdkp_ui_edit_attendance_form',
      'args' => array(),
    ),
    'edit-drop' => array(
      'form_id' => 'mewdkp_ui_edit_drop_form',
      'args' => array('drop_id'),
    ),
  );

  if ($key) {
    return !empty($forms[$key]) ? $forms[$key] : NULL;
  }

  return $forms;
}

/**
 * Build a form identifier that we can use to see if one form
 * is the same as another. Since the arguments differ slightly
 * we do a lot of spiffy concenation here.
 */
function mewdkp_ui_build_identifier($key, $raid, $kill_id, $args) {
  $form = mewdkp_ui_ajax_forms($key);
  $identifier = implode('-', array($key, $raid->nid, $kill_id));

  foreach ($form['args'] as $id) {
    $arg = (!empty($args)) ? array_shift($args) : NULL;
    $identifier .= '-' . $arg;
  }
  return $identifier;
}

/**
 * Build up a $form_state object suitable for use with drupal_build_form
 * based on known information about a form.
 */
function mewdkp_ui_build_form_state($js, $key, &$raid, $kill_id, $args) {
  $form = mewdkp_ui_ajax_forms($key);
  // Build up form state
  $form_state = array(
    'form_key' => $key,
    'form_id' => $form['form_id'],
    'raid' => &$raid,
    'ajax' => $js,
    'kill_id' => $kill_id,
    'no_redirect' => TRUE,
  );

  foreach ($form['args'] as $id) {
    $form_state[$id] = (!empty($args)) ? array_shift($args) : NULL;
  }

  return $form_state;
}

/**
 * Create the URL for one of our standard AJAX forms based upon known
 * information about the form.
 */
function mewdkp_ui_build_form_url($form_state) {
  $form = mewdkp_ui_ajax_forms($form_state['form_key']);
  $ajax = empty($form_state['ajax']) ? 'nojs' : 'ajax';
  $raid_nid = $form_state['raid']->nid;
  $url = "mewdkp/editor/$ajax/$form_state[form_key]/$raid_nid/$form_state[kill_id]";
  foreach ($form['args'] as $arg) {
    $url .= '/' . $form_state[$arg];
  }
  return $url;
}

/**
 * Add another form to the stack; clicking 'update' will go to this form
 * rather than closing the ajax pad.
 */
function mewdkp_ui_add_form_to_stack($key, &$raid, $kill_id, $args, $top = FALSE) {
  if (empty($raid->stack)) {
    $raid->stack = array();
  }

  $stack = array(mewdkp_ui_build_identifier($key, $raid, $kill_id, $args), $key, &$raid, $kill_id, $args);
  if ($top) {
    array_unshift($raid->stack, $stack);
  }
  else {
    $raid->stack[] = $stack;
  }
}

/**
 * Generic entry point to handle forms.
 *
 * We do this for consistency and to make it easy to chain forms
 * together. This only works for forms that use both $raid
 * and $kill_id, so we have a couple of ajax forms that we don't
 * use with this system.
 */
function mewdkp_ui_ajax_form($js, $key, &$raid, $kill_id) {
  $form = mewdkp_ui_ajax_forms($key);
  if (empty($form)) {
    return drupal_not_found();
  }

  _mewdkp_include('ajax');
  $args = func_get_args();
  // Remove the known args
  array_splice($args, 0, 4);

  $form_state = mewdkp_ui_build_form_state($js, $key, $raid, $kill_id, $args);
	
	
	
  // check to see if this is the top form of the stack. If it is, pop
  // it off; if it isn't, the user clicked somewhere else and the stack is
  // now irrelevant.
  if (!empty($raid->stack)) {
    $identifier = mewdkp_ui_build_identifier($key, $raid, $kill_id, $args);
    $top = array_shift($raid->stack);
    if (array_shift($top) != $identifier) {
      $raid->stack = array();
    }
  }

  $output = mewdkp_ajax_form_wrapper($form_state['form_id'], $form_state);
	
	

  if (!$output) {
    // Sometimes we need to re-generate the form for multi-step type operations.
    $object = NULL;
    if (!empty($raid->stack)) {
      $stack = $raid->stack; // copy so the next shift doesn't break the array
      $top = array_shift($stack);
      $top[0] = $js; // change identifier into $js setting
      $form_state = call_user_func_array('mewdkp_ui_build_form_state', $top);
      $form_state['input'] = array(); // this is a new form, make sure it
      // doesn't try to inherit $_POST info.
      if (!$js) {
        return drupal_goto(mewdkp_ui_build_form_url($form_state));
      }
      $object = mewdkp_ajax_form_wrapper($form_state['form_id'], $form_state);
      $object->url = url(mewdkp_ui_build_form_url($form_state));
    }
    else if (!$js) {
      // if nothing on the stack, non-js forms just go back to the main raid editor.
      return drupal_goto("node/$raid->nid");
    }
    // regenerate all tabs because changes to the default tab could ripple.
		if ($key == 'remove-kill'){
			return mewdkp_ui_regenerate_tabs($raid, $kill_id, $object);
		}
		return mewdkp_ui_regenerate_tabs($raid, NULL, $object);
  }

  return ($js) ? mewdkp_ajax_render($output) : $output;
}

/**
 * AJAX callback to add a kill.
 */
function mewdkp_ui_add_kill($js, $raid) {
  _mewdkp_include('ajax');
  $form_state = array(
    'raid' => &$raid,
    'ajax' => $js,
  );

  $output = mewdkp_ajax_form_wrapper('mewdkp_ui_add_kill_form', $form_state);

  if ($js) {
    // If we don't have an output object, it was submitted. Set up the submission.
    if (empty($output)) {
      $id = $form_state['id'];

      // Render the new kill
      list($title, $body) = mewdkp_ui_display_tab($raid, $raid->kills[$id]);

      // Instruct the javascript on the browser to render the new tab.
      $output = new stdClass;
      $output->tab = array('#mewdkp-tab-' . $id => array('title' => $title, 'body' => $body));
    }
    // Render the command object. This automatically exits.
    mewdkp_ajax_render($output);
  }

  // But the non-js variant will return output if it didn't redirect us.
  return $output;
}

/**
 * Form to add a kill to a raid.
 */
function mewdkp_ui_add_kill_form(&$form_state) {
  $raid = &$form_state['raid'];
	//$default_option = db_result(db_query("SELECT nid FROM {node} WHERE type = 'mob' AND title = 'Trash mob'"));

	//Default selection value
	
	$form['kill']['selected_kill'] = array(
		'#type' => 'hidden',
		'#default_value' => 0,
	);

  $form['kill']['kill'] = array(
    '#type' => 'select',
    '#options' => mewdkp_fetch_options_mobs($raid)
  );

  $form['kill']['add_kill'] = array(
    '#type' => 'submit',
    '#value' => t('Add boss kill'),
    '#submit' => array('mewdkp_ui_add_kill_form_submit'),
  );

  $form['#id'] = 'mewdkp-add-kill-form';
  $form['#attributes'] = array('class' => 'mewdkp-ajax-form');
  $form['#action'] = url("mewdkp/editor/nojs/add-kill/$raid->nid");

  return $form;
}

/**
 * Submit handler to add a kill to a raid
 */
function mewdkp_ui_add_kill_form_submit($form, &$form_state) {
  // Create the kill
	$raid = &$form_state['raid'];
	$mob = node_load($form_state['values']['kill']);
	$attendance_copy = $raid->kills[$form_state['values']['selected_kill']]['attendance'];
	$raid->kills[] = array(
		'attendance' => $attendance_copy,
		'nid' => $mob->nid,
		'name' => $mob->title,
		'drops' => array()
	);

  // Store in cache
  mewdkp_ui_cache_set($raid);
	
	$form_state['id'] = count($raid->kills)-1;
	
  // Send it back
  $form_state['redirect'] = array('node/' . $raid->nid . '/editraid', NULL, 'mewdkp-tab-' . $form_state['id']);
}

/**
 * Form to remove a kill from a raid.
 */
function mewdkp_ui_remove_kill_form(&$form_state) {
  $raid = &$form_state['raid'];
  $kill_id = $form_state['kill_id'];
	
	$form['kill'] = array(
		'#prefix' => '<div class="kill-button remove-kill">',
		'#suffix' => '</div>',
	);
	$form['remove_kill'] = array(
		'#type' => 'submit',
		'#value' => t('Remove kill'),
		'#submit' => array('mewdkp_ui_remove_kill_form_submit'),
	);

  $form['#action'] = url("mewdkp/editor/nojs/remove-kill/$raid->nid/$kill_id");
  $form['#attributes'] = array('class' => 'mewdkp-ajax-form');
	
	

  return $form;
}

/**
 * Submit handler to remove a kill from a raid.
 */
function mewdkp_ui_remove_kill_form_submit($form, &$form_state) {
	$raid = &$form_state['raid'];
	unset($raid->kills[$form_state['kill_id']]);
	mewdkp_ui_cache_set($raid);
}

/**
 * Form to add_drop drops in the raid UI.
 */
function mewdkp_ui_add_drop_form(&$form_state) {
  $raid = &$form_state['raid'];
  $kill_id = $form_state['kill_id'];

  $kill = $raid->kills[$kill_id];

  $form['#title'] = $kill['name'] . ': ';
  $form['#title'] .= t('Add drop');
  $form['#section'] = $kill_id . '-drop-add';
	
	$options = mewdkp_fetch_options_drops($kill['nid']);
	
  if (!empty($options)) {		
		//Add form item to select drop
		$form['drop'] = array(
			'#type' => 'select',
			'#required' => TRUE,
			'#title' => t('Select item'),
			'#options' => $options,
		);
		
		//Add winner selection.  This should get all currently active players as an otpion array. TO DO: Implement
		$form['winner'] = array(
			'#type' => 'select',
			'#required' => TRUE,
			'#title' => t('Select winner'),
			'#options' => mewdkp_fetch_options_players(TRUE)
		);
		
		$form['disenchanted'] = array(
			'#type' => 'checkbox',
			'#title' => t('Disenchanted'),
			'#default_value' => FALSE
		);
		
		$form['override'] = array(
			'#type' => 'textfield',
			'#title' => t('Price Override'),
			'#default_value' => '',
			'#maxlength' => 4,
			'#size' => 4
		);
		
		mewdkp_ui_standard_form_buttons($form, $form_state, 'mewdkp_ui_add_drop_form', t('Add'));
  }
  else {
    $form['markup'] = array(
      '#value' => '<div class="form-item">' . t('There are no drops available to add.', array('@types' =>  $types[$type]['ltitle'])) . '</div>',
    );
  }

  return $form;
}

/**
 * Submit handler for adding a new drop to a raid.
 */
function mewdkp_ui_add_drop_form_submit($form, &$form_state) {
	$raid = &$form_state['raid'];
	
  if (!empty($form_state['values']['drop'])) {
		$item = node_load($form_state['values']['drop']);
		$note = '';
		if ($form_state['values']['disenchanted']){
			$note = 'DE';
		} elseif ($form_state['values']['override'] != '' && is_numeric($form_state['values']['override'])) {
			$note = $form_state['values']['override'];
		}
		$drop = array(
			'wowid' => $item->field_mewdkp_wowid[0]['value'],
			'winner' => $form_state['values']['winner'],
			'count' => 1,
			'name' => $item->title,
			'nid' => $item->nid,
			'note' => $note,
		);
		$raid->kills[$form_state['kill_id']]['drops'][] = $drop;
  }

  // Store in cache
  mewdkp_ui_cache_set($raid);
}


/**
 * Form to edit_drop drops in the raid UI.
 */
function mewdkp_ui_edit_drop_form(&$form_state) {
  $raid = &$form_state['raid'];
  $kill_id = $form_state['kill_id'];
  $id = $form_state['drop_id'];	

  $form = array('options' => array('#tree' => TRUE));	
	
	$drop = $raid->kills[$kill_id]['drops'][$id];
	
	//TO DO: Implement this
	$drops = mewdkp_fetch_options_drops($raid->kills[$kill_id]['nid']);

  if ($drop) {
		$form['#title'] = t('Edit drop "@item"', array('@item' => $drop['name']));

		$form['#section'] = $kill_id . '-drop-' . $id;

		//Add form item to select drop
		$form['drop'] = array(
			'#type' => 'select',
			'#required' => TRUE,
			'#title' => t('Select item'),
			'#options' => $drops,
			'#default_value' => $drop['nid']
		);
		
		//Add winner selection.  This should get all currently active players as an option array. TO DO: Implement
		$form['winner'] = array(
			'#type' => 'select',
			'#required' => TRUE,
			'#title' => t('Select winner'),
			'#options' => mewdkp_fetch_options_players(TRUE),
			'#default_value' => $drop['winner']
		);
		
		$form['disenchanted'] = array(
			'#type' => 'checkbox',
			'#title' => t('Disenchanted'),
			'#default_value' => ($raid->kills[$kill_id]['drops'][$id]['note'] == 'DE')
		);
		
		$price_override = (is_numeric($drop['note'])?($drop['note']):(''));
		$form['override'] = array(
			'#type' => 'textfield',
			'#title' => t('Price Override'),
			'#default_value' => $price_override,
			'#maxlength' => 4,
			'#size' => 4
		);
		
    $name = NULL;
    if (isset($form_state['update_name'])) {
      $name = $form_state['update_name'];
    }
		
		mewdkp_ui_standard_form_buttons($form, $form_state, 'mewdkp_ui_edit_drop_form', $name, t('Remove'), 'remove');
  }
  return $form;
}

/**
 * Validate handler for adding a drop to a raid.
 */
function mewdkp_ui_edit_drop_form_validate($form, &$form_state) {
  //TO DO: Possible validation?
}

/**
 * Submit handler for adding a drop to a raid.
 */
function mewdkp_ui_edit_drop_form_submit($form, &$form_state) {
	$raid = &$form_state['raid'];
	$drop_id = $form_state['drop_id'];
	
  if (!empty($form_state['values']['drop'])) {
		$item = node_load($form_state['values']['drop']);
		$note = '';
		if ($form_state['values']['disenchanted']){
			$note = 'DE';
		} elseif ($form_state['values']['override'] != '' && is_numeric($form_state['values']['override'])) {
			$note = $form_state['values']['override'];
		}
		$drop = array(
			'wowid' => $item->field_mewdkp_wowid[0]['value'],
			'winner' => $form_state['values']['winner'],
			'count' => 1,
			'name' => $item->title,
			'nid' => $item->nid,
			'note' => $note,
		);
		$raid->kills[$form_state['kill_id']]['drops'][$drop_id] = $drop;
  }

  // Store in cache
  mewdkp_ui_cache_set($raid);
}

/**
 * Submit handler for removing a drop from a raid
 */
function mewdkp_ui_edit_drop_form_remove($form, &$form_state) {
  $raid = &$form_state['raid'];
	unset($raid->kills[$form_state['kill_id']]['drops'][$form_state['drop_id']]);
	mewdkp_ui_cache_set($raid);
}

/**
 * Form to edit raid attendance per kill.
 */
function mewdkp_ui_edit_attendance_form(&$form_state) {
  $raid = &$form_state['raid'];
  $kill_id = $form_state['kill_id'];

  $form = array('options' => array('#tree' => TRUE));
	
	$form['#section'] = $kill_id . '-attendance';
	
	//Get active players.
	$options = mewdkp_fetch_options_players(FALSE);	
	if (!empty($options)){		
		$form['attendance'] = array(
			'#type' => 'checkboxes',
			'#title' => t('Attendance'),
			'#options' => $options,
			'#default_value' => $raid->kills[$kill_id]['attendance'],
			'#prefix' => '<div class="mewdkp-attendance-checkboxes">',
			'#suffix' => '<div style="clear:both"></div></div>'
		);
		
    $name = NULL;
    if (isset($form_state['update_name'])) {
      $name = $form_state['update_name'];
    }
		
		mewdkp_ui_standard_form_buttons($form, $form_state, 'mewdkp_ui_edit_attendance_form', $name);
  }
  return $form;
}

/**
 * Handler function for setting attendance.
 **/
function mewdkp_ui_edit_attendance_form_submit($form, &$form_state){
	$raid = &$form_state['raid'];
	$kill_id = $form_state['kill_id'];
	
	$attendance = array();
	foreach($form_state['values']['attendance'] as $nid => $value){
		if ($value > 0){
			$attendance[] = $nid;
		}
	}
	
	$raid->kills[$kill_id]['attendance'] = $attendance;
	
	mewdkp_ui_cache_set($raid);
}
// ------------------------------------------------------------------

/**
 * Sorts a nested attendance array by a given field
 */
function _mewdkp_sort_attendance(&$source, $field = 'name', $asc = 'asc') {
	$sortArr = array();
 
	foreach ($source as $key => $value) {
		$sortArr[$key] = $value[$field];
	}

	if ($asc == 'desc')	{
		arsort( $sortArr );
	}
	else {
		asort( $sortArr );
	}
 
	$resultArr = array();
	foreach ($sortArr as $key => $value) {
		$resultArr[$key] = $source[$key];
	}

	$source = $resultArr;
	return $source;
}


/**
 * Fetch a list of all mobs available in the raid's zone.
 */
function mewdkp_fetch_options_mobs($raid) {
  $zone_nid = $raid->field_mewdkp_zone[0]['nid'];
	$result = db_query("
		(SELECT m.nid, m.title FROM {content_type_mewdkp_mob} cm
			LEFT JOIN {content_field_mewdkp_zone} fzone ON fzone.nid = cm.nid
			LEFT JOIN {node} m ON m.nid = cm.nid
		WHERE
			fzone.field_mewdkp_zone_nid = %d
		ORDER BY m.title ASC)
			UNION	(SELECT m.nid, m.title FROM {content_type_mewdkp_mob} cm LEFT JOIN {node} m ON m.nid = cm.nid	WHERE m.title = '%s')
		", $zone_nid, 'Trash mob');
	$options = array();
	while ($row = db_fetch_object($result)) {
		$options[$row->nid] = $row->title;
	}
  return $options;
}

/**
 * Fetch a list of all drops available from a specific mob.
 */
function mewdkp_fetch_options_drops($mob_nid) {
	$result = db_query("
		SELECT i.nid, i.title FROM {content_type_mewdkp_item} ci
			LEFT JOIN {content_field_mewdkp_mob} fmob ON fmob.nid = ci.nid
			LEFT JOIN {node} i ON i.nid = ci.nid
		WHERE
			fmob.field_mewdkp_mob_nid = %d AND
			ci.field_mewdkp_exclude_value = 0
		ORDER BY i.title ASC", $mob_nid);
	$options = array();
	while ($row = db_fetch_object($result)) {
		$options[$row->nid] = $row->title;
	}			
  return $options;
}

/**
 * Fetch a list of all active players
 * sorted alphabeically, with the bank at the bottom is applicable,
 * as an option array.
 **/
function mewdkp_fetch_options_players($bank = FALSE) {
	$query = "
		SELECT cp.nid, cp.field_mewdkp_player_name_value AS name 
		FROM {content_type_mewdkp_player} cp
		WHERE
			cp.field_mewdkp_player_name_value != 'Bank'
		ORDER BY cp.field_mewdkp_player_name_value ASC";
	$result = db_query($query); //TO DO: Add active/inactive validation?
			
	$users = array();
	while ($rec = db_fetch_object($result)){
		$users[$rec->nid] = $rec->name;
	}
	
	//Add bank if applicable.  For some reason adding it inside the query destroys ordering
	//and I wanted it at the bottom of the list.
	if (variable_get('mewdkp_use_bank', TRUE) && $bank){
		$res = db_query("SELECT cp.nid, cp.field_mewdkp_player_name_value AS name 
		FROM {content_type_mewdkp_player} cp WHERE cp.field_mewdkp_player_name_value = 'Bank'");
		$bank = db_fetch_object($res);
		$users[$bank->nid] = $bank->name;
	}

	return $users;	
}

/**
 * Provide a list of object types used in a raid, with some information
 * about them.
 */
function mewdkp_ui_types() {
  static $retval = NULL;

  // statically cache this so t() doesn't run a bajillion times.
  if (!isset($retval)) {
    $retval = array(
      'drop' => array(
        'title' => t('Drops'), // title
        'ltitle' => t('drops'), // lowercase title for mid-sentence
        'stitle' => t('Drop'), // singular title
        'lstitle' => t('drop'), // singular lowercase title for mid sentence
        'plural' => 'drops',
      ),
      'attendance' => array(
        'title' => t('Attendance'),
        'ltitle' => t('attendance'),
        'stitle' => t('Attending player'),
        'lstitle' => t('attending player'),
        'plural' => 'Attendance',
      ),
    );
  }

  return $retval;
}
